package com.example.demo.service;
import com.example.demo.mapper.TeacherCourseMapper;
import com.example.demo.entity.TeacherCourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class TeacherCourseService {

    @Autowired
    private TeacherCourseMapper mapper;

    // 建立教师与课程的关联
    public Optional<TeacherCourse> createAssociation(String teacherId, String courseId) {
        // 1. 业务校验：检查关联是否已存在
        if (mapper.findByTeacherIdAndCourseId(teacherId, courseId).isPresent()) {
            // 关联已存在，返回空 Optional 或抛出自定义异常
            return Optional.empty();
        }

        // 2. 创建并插入
        TeacherCourse association = new TeacherCourse();
        association.setTeacherId(teacherId);
        association.setCourseId(courseId);

        // 注意：数据库外键约束会保证 teacherId 和 courseId 存在。
        try {
            if (mapper.insert(association) > 0) {
                return Optional.of(association); // 返回包含生成的ID的关联对象
            }
        } catch (Exception e) {
            // 捕获由于外键约束失败（teacherId 或 courseId 不存在）导致的数据库异常
            throw new RuntimeException("创建关联失败，请检查教师工号或课程ID是否存在。", e);
        }
        return Optional.empty();
    }

    // 解除教师与课程的关联
    public boolean deleteAssociation(String teacherId, String courseId) {
        return mapper.deleteByTeacherIdAndCourseId(teacherId, courseId) > 0;
    }

    // 查询某个教师教授的所有课程关联记录
    public List<TeacherCourse> findAssociationsByTeacherId(String teacherId) {
        return mapper.findByTeacherId(teacherId);
    }

    // 查询某个课程对应的所有教师关联记录
    public List<TeacherCourse> findAssociationsByCourseId(String courseId) {
        return mapper.findByCourseId(courseId);
    }
}